package classpath

import (
	"os"
	"path/filepath"
	"strings"
	"sync"
)

/*
由于wildcardEntry 本质上就是 compositeEntry 所以就不再定义新的类型了
使用异步操作来防止walk还未结束，newWildcardEntry就返回了空数组
*/
func newWildcardEntry(path string) CompositeEntry {
	baseDir := path[:len(path)-1]
	compositeEntry := []Entry{}
	var wg sync.WaitGroup
	wg.Add(1)
	// 回调函数，用于处理获取到的子路径
	walkFn := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() && path != baseDir {
			return filepath.SkipDir
		}
		if strings.HasSuffix(path, ".jar") || strings.HasSuffix(path, ".JAR") {
			jarEntry := newZipEntry(path)
			compositeEntry = append(compositeEntry, jarEntry)
		}
		return nil
	}

	go func() {
		defer wg.Done()
		filepath.Walk(baseDir, walkFn)
	}()

	wg.Wait()
	return compositeEntry
}
